package pub.cleangao.codegen.util;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.StringReader;
import java.io.StringWriter;

/**
 * 格式化输出XML文档
 */
@Slf4j
public class XmlFormatter {

    public static String prettify(String input) {
        try {
            SAXReader reader = new SAXReader();
            StringReader in = new StringReader(input);
            Document doc = reader.read(in);
            OutputFormat formatter = OutputFormat.createPrettyPrint();
            formatter.setEncoding("utf-8");
            formatter.setIndent("    ");
            StringWriter out = new StringWriter();
            XMLWriter writer = new XMLWriter(out, formatter);
            writer.write(doc);
            writer.close();
            return out.toString();
        } catch (Exception e) {
            log.error("XML格式化错误: {}", e.getMessage());
            return input;
        }
    }


}
